<?php

use Illuminate\Database\Eloquent\SoftDeletingTrait;
use Illuminate\Auth\UserTrait;
use Illuminate\Auth\UserInterface;
use Illuminate\Auth\Reminders\RemindableTrait;
use Illuminate\Auth\Reminders\RemindableInterface;

class User extends Eloquent implements UserInterface, RemindableInterface{

	use SoftDeletingTrait;
	use UserTrait, RemindableTrait;

	public $timestamps   = true;
	protected $dates     = ['deleted_at'];
	protected $table     = 'user';
	protected $validator = null;
	protected $hidden    = array('password', 'remember_token');

	public function saveData($data){
		$user = new User;

		if(isset($data['id']) && $data['id'] > 0){
			$user = User::firstOrNew(array('id' => $data['id']));
		}

		$user->name         = $data['name'];
		$user->email        = $data['email'];
		$user->phone_number = $data['phone_number'];
		$user->active       = $data['active'];
		$user->group        = $data['group'];
		$user->password     = $data['password'];
		$user->save();
		Cache::forget('user-all-data');

		return $user;
	}

	public function getAllData(){
		if(!Cache::has('user-all-data')){
			$data = UserGroup::all();
			Cache::put('user-all-data', $data, 30);
		}

		$data = Cache::get('user-all-data');

		return $data;
	}

	public function setPasswordAttribute($pass){
		$this->attributes['password'] = Hash::make($pass);
	}

	public function validator($data){
		$id = (isset($data['id']))? $data['id'] : "NULL";

		$rules = array(
			'name'         => array('required', 'alpha_num_spaces'),
			'email'        => array('required', 'email', 'unique:user,email,' . $id . ',id,deleted_at,NULL'),
			'phone_number' => array('numeric'),
			'password'     => array('required', 'min:8', 'max:30'),
			'repassword'   => array('required', 'same:password'),
			);

		$this->validator = Validator::make($data, $rules);

		return $this->validator;
	}

	public function getErrorMessages(){
		$messages = $this->validator->messages();
		
		$result   = array();

		foreach($messages->all() as $m){
			$result[]['message'] = $m;
		}

		return $result;
	}
}
